﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Flagwind.Data
{
	/// <summary>
	/// Command 动态排序对象，用于Command表达式的OrderBy参数
	/// </summary>
	public class SortOrder
	{
		private string orderString = string.Empty;
		private Command CurrentCommand;

		/// <summary>
		/// 获取排序字符串，Command内部使用
		/// </summary>
		public string OrderByString
		{
			get
			{
				return orderString;
			}
		}

		public SortOrder(Command command)
		{
			this.CurrentCommand = command;
		}

		/// <summary>
		/// 以一个实体类对象初始化构造函数
		/// </summary>
		/// <param name="entity"></param>
		[Obsolete("构造函数已经过时，请使用其它构造函数")]
		public SortOrder(IEntity entity)
		{
		}

		/// <summary>
		/// 以一个或者多个实体类，来构造排序条件类。在Command多实体类关联查询中需要使用该方法。
		/// </summary>
		/// <param name="e"></param>
		/// <param name="joinedEntitys"></param>
		[Obsolete("构造函数已经过时，请使用其它构造函数")]
		public SortOrder(IEntity e, params IEntity[] joinedEntitys)
		{
		}

		private SortOrder OrderBy(object field, string orderType)
		{
			if(CurrentCommand == null)
			{
				throw new InvalidOperationException("当前对象实例化的时候需要使用关联的Command实例，但使用了过期的构造函数。");
			}
			orderString += "," + CurrentCommand.TakeStackFields() + " " + orderType;
			CurrentCommand.fieldStack.Clear();
			return this;
		}

		/// <summary>
		/// 默认排序（ASC）
		/// </summary>
		/// <param name="field">要排序的实体属性</param>
		/// <returns></returns>
		public SortOrder OrderBy(object field)
		{
			return OrderBy(field, "ASC");
		}

		/// <summary>
		/// 升序排序ASC
		/// </summary>
		/// <param name="field">要排序的实体属性</param>
		/// <returns></returns>
		public SortOrder Asc(object field)
		{
			return OrderBy(field, "ASC");
		}

		/// <summary>
		/// 倒序排序DESC
		/// </summary>
		/// <param name="field">要排序的实体属性</param>
		/// <returns></returns>
		public SortOrder Desc(object field)
		{
			return OrderBy(field, "DESC");
		}

		/// <summary>
		/// 重置排序状态
		/// </summary>
		public void ReSet()
		{
			//currPropName = string.Empty;
			orderString = string.Empty;
		}

		/// <summary>
		/// 获取排序信息
		/// </summary>
		/// <returns></returns>
		override public string ToString()
		{
			return orderString.Substring(1);
		}
	}
}